﻿#region License statement
// NJamb, a specification and delta-specification DSL
// Copyright (c) 2010-2011, Mark Knell
// Published under the MIT License; all other rights reserved
#endregion

#region using...
using System.ComponentModel;
using NJamb.Parser.Subjects;
using Stile.Patterns.Disposables;
using Stile.Patterns.SelfDescribingPredicates;
#endregion

namespace NJamb.Specifications.Simple
{
	public class RaisePropertyChangedBeforeSpecification<TSource> : Disposable,
		IRaisePropertyChangedSpecification<TSource>
		where TSource : class, INotifyPropertyChanged
	{
		private string _actualPropertyName;
		private TSource _source;

		public RaisePropertyChangedBeforeSpecification(ICollaboratingSubject<TSource> collaboratingSubject)
		{
			_source = collaboratingSubject.Get();
		}

		public IEvaluation<string> Evaluate()
		{
			_source.PropertyChanged -= SourceOnPropertyChanged;
			_source.PropertyChanged += SourceOnPropertyChanged;
			return new Evaluation<string>(_actualPropertyName);
		}

		protected override void Disposing()
		{
			if (_source != null)
			{
				_source.PropertyChanged -= SourceOnPropertyChanged;
			}
			_source = null;
		}

		private void SourceOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
		{
			_actualPropertyName = propertyChangedEventArgs.PropertyName;
		}
	}
}
